package com.fdb.efp.console.executor;

import com.fdb.basic.framework.core.exception.FlowException;
import com.fdb.basic.framework.core.util.SpringContextUtils;
import com.fdb.efp.console.common.service.Executor;
import com.fdb.efp.console.common.vo.EngineVO;
import com.fdb.efp.console.enumeration.RouteTypeBean;
import com.fdb.efp.console.service.facade.BizFlowRouteService;
import com.fdb.efp.console.service.vo.BizFlowRouteVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 
 * 路由执行器
 * 
 * @author Cytus_
 * @since 2018年5月7日 下午9:16:09
 * @version 1.0
 *
 */
@Service("routeExecutor")
public class RouteExecutor implements Executor {
	
	private static Logger logger = LoggerFactory.getLogger(RouteExecutor.class);
	
	@Autowired
	@Qualifier("bizFlowRouteService")
	private BizFlowRouteService bizFlowRoutService;
	
	public EngineVO execute(EngineVO evo) throws FlowException {
		
		List<BizFlowRouteVO> routes = getCurrNodeRoutes(evo.getEventId(), evo.getNodeId(), evo.getFlowId());
		logger.info("事件编号："+ evo.getEventId() +", 节点编号："+ evo.getNodeId() +"执行路由信息开始......");
		evo.setPreNodeId(evo.getNodeId());
		if (Objects.isNull(routes) || routes.isEmpty()) {
			evo.setNodeId(null);
		} else if (routes.size() == 1) {
			BizFlowRouteVO defRoute = routes.get(0);
			evo.setNodeId(defRoute.getBizTargetNodeId());
		} else {
			try {
				evo.setNodeId(null);
				BizFlowRouteVO vo = null;
				for (BizFlowRouteVO route : routes) {
					RoutePluginExecutor routePluginExecutor = (RoutePluginExecutor) SpringContextUtils.getBean(RouteTypeBean.getPluginTypeBeanValue("default"));
					if (routePluginExecutor.isDefault(route)) {
					    vo = route;
					    continue;
					}
					boolean routeResult = routePluginExecutor.judgeRoute(evo, route);
					if (routeResult) {
					    vo = route;
						break;
					}
				}
				if (Objects.nonNull(vo))
				    evo.setNodeId(vo.getBizTargetNodeId());
			} catch (Exception e) {
				logger.error("事件编号："+ evo.getEventId() +", 节点编号："+ evo.getNodeId() +"执行路由信息出现异常!", e);
				throw new FlowException(e.getMessage(), e);
			}
			
		}
		logger.info("事件编号："+ evo.getEventId() +", 节点编号："+ evo.getPreNodeId() +"执行路由信息结束, 下一待执行节点信息为："+ evo.getNodeId());
		return evo;
	}

	public List<BizFlowRouteVO> getCurrNodeRoutes(String eventId, String srouceNodeId, String flowId) {
		BizFlowRouteVO vo = new BizFlowRouteVO();
		vo.setBizEventId(eventId);
		vo.setBizSourceNodeId(srouceNodeId);
		vo.setBizFlowId(flowId);
		return this.bizFlowRoutService.queryAllBySourceNodeId(vo);
	}
	
	
}
